module("luci.controller.admin.wifiscan", package.seeall)
function index()
	entry({"admin", "wifiscan"},template("admin_wifi/wifiscan"), _("WIFI Scan"), 2)
	entry({"admin", "wifiscan","ConfigScan"},call("ConfigScan_json"),nil, nil).leaf=true

	entry({"admin", "wifiscan","APdeviceinfo"},template("admin_wifi/APdeviceinfo"),nil, nil).leaf=true
	entry({"admin", "wifiscan","APDevInfo"},call("APDevInfo_json"),nil, nil).leaf=true

	entry({"admin", "wifiscan","Terminalequipinfo"},template("admin_wifi/Terminalequipinfo"),nil, nil).leaf=true
	entry({"admin", "wifiscan","TerminalDevInfo"},call("TerminalDevInfo_json"),nil, nil).leaf=true

	entry({"admin", "wifiscan","DatabaseClear"},call("DatabaseClear"),nil, nil).leaf=true

	entry({"admin", "wifiscan","PackageCrack"},template("admin_wifi/PackageCrack"),nil, nil).leaf=true
	entry({"admin", "wifiscan","PackageGet"},call("PackageGet"),nil, nil).leaf=true
	entry({"admin", "wifiscan","PackageList"},call("PackageList"),nil, nil).leaf=true
	entry({"admin", "wifiscan","PackageAct"},call("PackageAct"),nil, nil).leaf=true
	entry({"admin", "wifiscan","PackageClear"},call("PackageClear"),nil, nil).leaf=true

	entry({"admin", "wifiscan","APAttack"},template("admin_wifi/APAttack"),nil, nil).leaf=true
	entry({"admin", "wifiscan","APAttackAct"},call("APAttackAct"),nil, nil).leaf=true
	entry({"admin", "wifiscan","wificrack"},call("wificrack"),nil, nil).leaf=true
	entry({"admin", "wifiscan","WZWifi"},call("WZWifiAct"),nil, nil).leaf=true
	entry({"admin", "wifiscan","APCamouflageAct"},call("APCamouflageAct"),nil, nil).leaf=true


end

function APCamouflageAct(action)

    local acstat=""
    local function ActStat()
	     acstat = luci.util.exec("cat /tmp/wififake")

	    if("start" == action)
	    then
		    acstat = io.popen("echo 1 > /tmp/wififake ; wififake start")
			acstat:close()
	        return "stop"

	    end

	    if("stop" == action)
		then
		    acstat = luci.util.exec("echo 0 > /tmp/wififake ; wififake stop")
			return "start"

		end

		if("status" == action )
		then

			if(string.find(acstat,'1',1))
			then
				return "runing"

			else
				return "unruning"
			end

		end

		--return "action "..acstat.."error!"
	end


    luci.http.prepare_content("application/json")
	luci.http.write('[')
	luci.http.write_json(ActStat(action))
	luci.http.write(']')
end

function DatabaseClear(dbName)
	local datbaseURL='/mnt/sda1/MACInfo.db'
	local sqlite3 = require('lsqlite3')
	local sqlCmd='delete from '..dbName..';'
	local file =io.open(datbaseURL, "r")     --judge  the existence of the device database
	local AParray={ }

	luci.util.exec("echo 1 > /proc/wifigrap/macclear")
	if not file then
			return ""
	end




	file:close()

	local Devdb = sqlite3.open(datbaseURL, sqlite3.OPEN_READWRITE)

	if Devdb==nil then
		return ""
	end



	Devdb:execute(sqlCmd)

	Devdb:close()



end

function PackageClear()
     luci.util.exec("rm -rf /mnt/sda1/cap/*")
end

function wificrack(sigpath,apmac,srcmac)

    local function crack()
	    local crackstat = io.popen(" wificrack start "..signalPath.." "..apmac.." "..srcmac.." ")
		crackstat:close()
	    luci.util.exec("echo "..sigpath.."/"..apmac.."/"..srcmac.." > /tmp/wificrackstat")
		--return "echo "..sigpath.."/"..apmac.."/"..srcmac.." > /tmp/wificrackstat"
	end
    luci.util.exec("echo "..sigpath.."/"..apmac.."/"..srcmac.." > /tmp/wificrackstat")
    --luci.http.prepare_content("application/json")
	--luci.http.write('[')
	--luci.http.write_json(crack())
	--luci.http.write(']')
end


function PackageAct(action,signalPath,apmac)
    local acstat=""
    local function ActStat()
	     acstat = luci.util.exec("cat /tmp/wificapstat")

	    if("start" == action)
	    then
		    acstat = io.popen("echo 1 > /tmp/wificapstat ; wificap start "..signalPath.." "..apmac.." ")
			acstat:close()
	        return "stop"

	    end

	    if("stop" == action)
		then
		    acstat = luci.util.exec("echo 0 > /tmp/wificapstat ; wificap stop")
			return "start"

		end

		if("status" == action )
		then

			if(string.find(acstat,'1',1))
			then
				return "runing"

			else                   --if(string.find(acstat,'0',1))
			                      --then
				return "unruning"
			end

		end

		--return "action "..acstat.."error!"
	end


    luci.http.prepare_content("application/json")
	luci.http.write('[')
	luci.http.write_json(ActStat(action))
	luci.http.write(']')
end


function APAttackAct(action,signalPath,apmac)
    local acstat=""
    local function ActStat()
	     acstat = luci.util.exec("cat /tmp/wifiattackstat")

	    if("start" == action)
	    then
		    acstat = io.popen("echo 1 > /tmp/wifiattackstat ; wifiattack start "..signalPath.." "..apmac.."")
			acstat:close()
	        return "stop"

	    end

	    if("stop" == action)
		then
		    acstat = luci.util.exec("echo 0 > /tmp/wifiattackstat ; wifiattack stop")
			return "start"

		end

		if("status" == action )
		then

			if(string.find(acstat,'1',1))
			then
				return "runing"

			else                   --if(string.find(acstat,'0',1))
			                      --then
				return "unruning"
			end

		end

		--return "action "..acstat.."error!"
	end


    luci.http.prepare_content("application/json")
	luci.http.write('[')
	luci.http.write_json(ActStat(action))
	luci.http.write(']')
end


function WZWifiAct(signalPath, ssid,encrypt,key)
    local UCI  = require "luci.model.uci"
    
    local function ActStat()    
        local x = UCI.cursor()   
        x:foreach("wireless", "wifi-iface",
            function(s)
                --print(s['.index'])
                x:set("wireless", s['.name'], "ssid" , ssid)
                x:set("wireless", s['.name'], "mode" , "ap")
                if encrypt == "WPA" then
                    x:set("wireless", s['.name'], "encryption" , "psk")
                    x:set("wireless", s['.name'], "key" , key)
                elseif encrypt == "WPA2" then
                    x:set("wireless", s['.name'], "encryption" , "psk2")
                    x:set("wireless", s['.name'], "key" , key)
                elseif encrypt == "WPA-WPA2" then
                    x:set("wireless", s['.name'], "encryption" , "psk-mixed")
                    x:set("wireless", s['.name'], "key" , key)
                elseif encrypt == "WEP" then
                    x:set("wireless", s['.name'], "encryption" , "wep-open")
                    x:set("wireless", s['.name'], "key" , "1")
                    x:set("wireless", s['.name'], "key1" , 's:'..key)
                else
                    x:set("wireless", s['.name'], "encryption" , "none")
                end
            end)
        x:commit("wireless")
        x:load("wireless")
        luci.util.exec("wifi down;")
        luci.util.exec("wifi up;")
    end


    luci.http.prepare_content("application/json")
    luci.http.write('[')
    luci.http.write_json(ActStat())
    luci.http.write(']')
end

function PackageList()
	local function listInfo()
	    local wifigrap=luci.util.exec("ls /mnt/sda1/cap | grep '.cap' > /mnt/packagelist ; cat /mnt/packagelist ; rm /mnt/packagelist" )

		return wifigrap
	end

	luci.http.prepare_content("application/json")
	luci.http.write('[')
	luci.http.write_json(listInfo())
	luci.http.write(']')
end

function PackageGet()

	local pagename=luci.http.formvalue("getpackage")

	local downcmd = "cat /mnt/sda1/cap/"..pagename.." "

    if pagename then

	    local reader = ltn12_popen(downcmd)
		    luci.http.header('Content-Disposition', 'attachment; filename="%s"' % {pagename})
		    luci.http.prepare_content("Content-Type", "text/html")
		    luci.ltn12.pump.all(reader, luci.http.write)
	end
end

function ltn12_popen(command)

	local fdi, fdo = nixio.pipe()
	local pid = nixio.fork()

	if pid > 0 then
		fdo:close()
		local close
		return function()
			local buffer = fdi:read(2048)
			local wpid, stat = nixio.waitpid(pid, "nohang")
			if not close and wpid and stat == "exited" then
				close = true
			end

			if buffer and #buffer > 0 then
				return buffer
			elseif close then
				fdi:close()
				return nil
			end
		end
	elseif pid == 0 then
		nixio.dup(fdo, nixio.stdout)
		fdi:close()
		fdo:close()
		nixio.exec("/bin/sh", "-c", command)
	end
end


function ConfigScan(action)

    local acfile=nil
	local wifigrap=io.popen("cat /proc/wifigrap/switch ")
	local scanStat=wifigrap:read("*all")
    wifigrap:close()

    if("start" == action)
	then
        acfile = io.popen("echo 1 >/proc/wifigrap/switch")
		acfile:close()
	    return "stop"

	end

	if("stop" == action)
    then
	    acfile = io.popen("echo 0 >/proc/wifigrap/switch")
		acfile:close()
	    return "start"

	end

	if("status" == action )
	then

	    if(string.find(scanStat,'1',1))
		then
		    return "runing"
		elseif(string.find(scanStat,'0',1))
		then
		    return "unruning"
		end

	end

    return "action "..scanStat.."error!"

end

function ConfigScan_json(action)
    luci.http.prepare_content("application/json")
	luci.http.write('[')
	luci.http.write_json(ConfigScan(action))
	luci.http.write(']')
end

function string_split(str,split_char)
	local pos = ""
	local sub_str_tab = { }

	local af=io.popen('echo '..str..' > /tmp/aplog')
	af:close()
   	while(true)
	do
		 pos = string.find(str,split_char)
		 if (not pos) then
            break
        end

		sub_str_tab[#sub_str_tab+1] = string.sub(str, 1,pos-1)

		str = string.sub(str, pos + 1, #str)
	end

    return sub_str_tab
end

function getAPDevInfo(param)

	local datbaseURL='/mnt/sda1/MACInfo.db'
	local sqlite3 = require('lsqlite3')
	local sqlCmd=''
	local file =io.open(datbaseURL, "r")     --judge  the existence of the device database
	local AParray={ }
	local apPar = { }
	local flag = 0

	if not file then
			return ""
	end

	file:close()

	local Devdb = sqlite3.open(datbaseURL, sqlite3.OPEN_READWRITE)

	if Devdb==nil then
		return ""
	end

    apPar = string_split(param," ")

	sqlCmd = "select * from APInfo where "

	local af=io.popen('echo '..apPar[1]..' >> /tmp/aplog')
	af:close()

	if  "nil" ~= apPar[1] then
		sqlCmd = sqlCmd..'essid like"%'..apPar[1]..'%" '
		flag = 1
	end

	if "nil" ~= apPar[2] then

		if flag > 0 then
			sqlCmd = sqlCmd..' and '
		end
		sqlCmd = sqlCmd..' s_mac like"%'..apPar[2]..'%" '
		flag = 1
	end

	if "nil" ~= apPar[3] then
		if flag > 0 then
			sqlCmd = sqlCmd..' and '
		end
		sqlCmd = sqlCmd..' speed="'..apPar[3]..'" '
		flag = 1
	end

	if "nil" ~= apPar[4] then
		if flag > 0 then
			sqlCmd = sqlCmd..' and '
		end
		sqlCmd = sqlCmd..' channel="'..apPar[4]..'" '
		flag = 1
	end

	if "nil" ~= apPar[5] then
		if flag > 0 then
			sqlCmd = sqlCmd..' and '
		end
		sqlCmd = sqlCmd..'en_mode like"%'..apPar[5]..'%" '
		flag = 1
	end


	sqlCmd = sqlCmd..";"

	if flag <= 0 then
		sqlCmd='select * from APInfo;'
		flag = 0
	end



	for row in Devdb:nrows(sqlCmd) do

		AParray[#AParray+1] = {

			ssid = row.essid,
			signalStrength = row.signal,
			mac = row.s_mac,
			frequency = row.speed,
			signalPath = row.channel,
			encryption = row.en_mode,
			devmodel =  "",
			devVersion = row.ver_name,
			devName =row.device_name,
			time    = row.time

		}
	end

	Devdb:close()

	return AParray

end

function APDevInfo_json(param)

    luci.http.prepare_content("application/json")
	luci.http.write('[')
	luci.http.write_json(getAPDevInfo(param))
	luci.http.write(']')
end

function getTerminalDevInfo(param)

	local TerminalArray={ }
	local datbaseURL='/mnt/sda1/MACInfo.db'
	local sqlite3 = require('lsqlite3')
	local sqlCmd='select * from STAInfo;'
	local tmPar = { }
	local flag = 0
	local file =io.open(datbaseURL, "r")     --judge  the existence of the device database

	if not file then
			return ""
	end

	file:close()

	local Devdb = sqlite3.open(datbaseURL, sqlite3.OPEN_READWRITE)

	if Devdb==nil then
		return ""
	end

	tmPar = string_split(param," ")

	local sqlCmd='select * from STAInfo where '

	if  "nil" ~= tmPar[1] then
		sqlCmd = sqlCmd..'s_mac like"%'..tmPar[1]..'%" '
		flag = 1
	end

	if "nil" ~= tmPar[2] then

		if flag > 0 then
			sqlCmd = sqlCmd..' and '
		end
		sqlCmd = sqlCmd..' d_mac like"%'..tmPar[2]..'%" '
		flag = 1
	end

	if "nil" ~= tmPar[3] then
		if flag > 0 then
			sqlCmd = sqlCmd..' and '
		end
		sqlCmd = sqlCmd..' b_mac like"%'..tmPar[3]..'%" '
		flag = 1
	end

	if "nil" ~= tmPar[4] then
		if flag > 0 then
			sqlCmd = sqlCmd..' and '
		end
		sqlCmd = sqlCmd..' essid like"%'..tmPar[4]..'%" '
		flag = 1
	end

	sqlCmd = sqlCmd..";"

	if flag <= 0 then
		sqlCmd='select * from STAInfo;'
		flag = 0
	end


	for row in Devdb:nrows(sqlCmd) do

		TerminalArray[#TerminalArray+1]={

			smac = row.s_mac,
			dmac = row.d_mac,
			imac = row.b_mac,
			requsetSSID = row.essid,
			devName = "",
			signalStrength = row.signal,
			time    = row.time,
			signalPath = row.channel,
		}

	end

	Devdb:close()

	return TerminalArray

end

function TerminalDevInfo_json(param)
    luci.http.prepare_content("application/json")
	luci.http.write('[')
	luci.http.write_json(getTerminalDevInfo(param))
	luci.http.write(']')
end
